package com.gzdh.device.comm.util;


import com.github.wxpay.sdk.WXPayConstants;
import org.apache.commons.httpclient.Cookie;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.util.StreamUtils;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;

import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.*;

import static com.github.wxpay.sdk.WXPayUtil.HMACSHA256;


public class HttpClientUtils {

    public static String doPost(String url, Map<String, String> map, String key) {
        HttpClient httpClient = new HttpClient();
        PostMethod method = new PostMethod(url);
        try {
            map.put("urlTime", String.valueOf(System.currentTimeMillis()));
            map.put("sign", generateSignature(map, key));
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            map.forEach((t, u) -> {
                nameValuePairs.add(new NameValuePair(t, u));
            });
            NameValuePair[] param = nameValuePairs.toArray(new NameValuePair[nameValuePairs.size()]);
            method.addParameters(param);

            int statusCode = httpClient.executeMethod(method);
            return StreamUtils.copyToString(method.getResponseBodyAsStream(), Charset.forName("utf-8"));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            method.releaseConnection();
        }
        return null;
    }


    public static String generateSignature(final Map<String, String> data, String key) throws Exception {
        Set<String> keySet = data.keySet();
        String[] keyArray = keySet.toArray(new String[keySet.size()]);
        Arrays.sort(keyArray);
        StringBuilder sb = new StringBuilder();
        for (String k : keyArray) {
            if (k.equals(WXPayConstants.FIELD_SIGN)) {
                continue;
            }
            if (data.get(k).trim().length() > 0) // 参数值为空，则不参与签名
                sb.append(k).append("=").append(data.get(k).trim()).append("&");
        }
        sb.append("key=").append(key);
        return HMACSHA256(sb.toString(), key);
    }
}